// 创建模板
const pieChartTemplate = document.createElement("template");
pieChartTemplate.innerHTML = `
    <style>
        :host {
            display: block;
            width: 100%;
            height: 100%;
        }
        .chart-container {
            width: 100%;
            height: 100%;
        }
    </style>
    <div class="chart-container"></div>
`;

class PieChartComponentSjbz extends HTMLElement {
    constructor() {
        super();

        // 创建 Shadow DOM
        const shadow = this.attachShadow({ mode: 'closed' });

        // 克隆模板内容
        shadow.appendChild(pieChartTemplate.content.cloneNode(true));

        // 获取图表容器
        const chartDiv = shadow.querySelector('.chart-container');

        // 初始化定时器和图表实例
        this.timerId = null;
        this.chart = echarts.init(chartDiv);
    }

    connectedCallback() {
        // 获取属性值，带默认值
        const titleColor = this.getAttribute('title-color') || 'black';
        const titleText = this.getAttribute('title-text') || '饼图数据';
        const titleFontSize = this.getAttribute('title-font-size') || 18;
        const legendColor = this.getAttribute('legend-color') || 'black';
        const legendPosition = this.getAttribute('legend-position') || 'right';
        const radius = this.getAttribute('radius') || '70%';
        const center = this.getAttribute('center') || '50%,50%';
        const labelShow = this.getAttribute('label-show') !== 'false'; // 默认显示标签
        const labelPosition = this.getAttribute('label-position') || 'outside';
        const dataUrl = this.getAttribute('data-url');
        const echartInitScript = this.getAttribute('echart-init-script');

        // 处理颜色列表
        let colorList = this.getAttribute('color-list') || 'blue,red,green,yellow,purple,橙色';
        colorList = colorList.split(',');

        // 调整初始大小
        this.resizeChart();

        // 监听 resize 事件
        window.addEventListener('resize', this.resizeChart.bind(this));

        // 观察父容器的大小变化
        if (ResizeObserver) {
            this.observer = new ResizeObserver(() => this.resizeChart());
            this.observer.observe(this.parentElement);
        }

        // 如果提供了数据URL，加载数据并渲染图表
        if (dataUrl) {
            fetch(dataUrl)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    // 处理饼图数据格式
                    const pieData = data.map(item => ({
                        name: item.name,
                        value: item.value
                    }));

                    // 设置图表选项
                    const option = {
                        title: {
                            text: titleText,
                            textStyle: {
                                color: titleColor,
                                fontSize: parseInt(titleFontSize)
                            },
                            left: 'center'
                        },
                        tooltip: {
                            trigger: 'item'
                        },
                        legend: {
                            show: true,
                            textStyle: {
                                color: legendColor
                            },
                            orient: legendPosition.includes('top') || legendPosition.includes('bottom') ? 'horizontal' : 'vertical',
                            left: legendPosition.includes('left') ? 'left' : undefined,
                            right: legendPosition.includes('right') ? 'right' : undefined,
                            top: legendPosition.includes('top') ? 'top' : undefined,
                            bottom: legendPosition.includes('bottom') ? 'bottom' : undefined,
                            center: legendPosition === 'center' ? 'center' : undefined
                        },
                        color: colorList,
                        series: [{
                            name: '数据类别',
                            type: 'pie',
                            radius: radius,
                            center: center.split(',').map(item => item.trim()),
                            data: pieData,
                            label: {
                                show: labelShow,
                                position: labelPosition,
                                formatter: '{b}: {c} ({d}%)'
                            },
                            labelLine: {
                                show: labelShow && labelPosition === 'outside',
                                length: 10,
                                length2: 5
                            },
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }]
                    };
                    this.chart.setOption(option);
                })
                .catch(error => {
                    console.error('Fetch operation error:', error);
                });
        }

        // 执行初始化脚本
        if (echartInitScript && echartInitScript !== "") {
            try {
                eval(echartInitScript);
            } catch (error) {
                console.log(error.message);
            }
        }
    }

    // 属性的 getter 和 setter 方法
    get titlecolor() {
        return this.getAttribute("title-color");
    }
    set titlecolor(value) {
        this.setAttribute("title-color", value);
    }

    get legendcolor() {
        return this.getAttribute("legend-color");
    }
    set legendcolor(value) {
        this.setAttribute("legend-color", value);
    }

    get colorlist() {
        return this.getAttribute("color-list");
    }
    set colorlist(value) {
        this.setAttribute("color-list", value);
    }

    get echartinitscript() {
        return this.getAttribute("echart-init-script");
    }
    set echartinitscript(value) {
        this.setAttribute("echart-init-script", value);
    }

    get echarttimerscript() {
        return this.getAttribute("echart-timer-script");
    }
    set echarttimerscript(value) {
        this.setAttribute("echart-timer-script", value);
    }

    get echarttimer() {
        return this.getAttribute("echart-timer");
    }
    set echarttimer(value) {
        this.setAttribute("echart-timer", value);
    }

    get dataurl() {
        return this.getAttribute("data-url");
    }
    set dataurl(value) {
        this.setAttribute("data-url", value);
    }

    // 监听的属性列表
    static get observedAttributes() {
        return [
            'title-text', 'title-color', 'title-font-size',
            'legend-color', 'legend-position',
            'color-list', 'radius', 'center',
            'label-show', 'label-position',
            'echart-timer', 'echart-init-script',
            'echart-timer-script', 'data-url'
        ];
    }

    // 组件断开连接时清理资源
    disconnectedCallback() {
        // 移除 resize 事件监听器
        window.removeEventListener('resize', this.resizeChart.bind(this));

        // 停止观察父容器的大小变化
        if (this.observer) {
            this.observer.disconnect();
        }

        // 清除定时器
        clearInterval(this.timerId);
    }

    // 设置定时器
    setTimer(interval) {
        // 清除之前的定时器
        clearInterval(this.timerId);
        if (interval > 0) {
            this.timerId = setInterval(() => {
                this.executeScript();
            }, interval);
        }
    }

    // 执行脚本
    executeScript() {
        if (this.echarttimerscript !== "") {
            try {
                eval(this.echarttimerscript);
            } catch (error) {
                console.log(error.message);
            }
        } else {
            console.log("no script to execute");
        }
    }

    // 调整图表大小
    resizeChart() {
        this.chart.resize();
    }

    // 获取图表实例
    getChartInstance() {
        return this.chart;
    }

    // 更新数据
    async updateData() {
        try {
            const fullUrl = this.dataurl;
            const response = await fetch(fullUrl);
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            const data = await response.json();
            if (data) {
                // 转换数据格式为饼图所需
                const pieData = data.map(item => ({
                    name: item.name,
                    value: item.value
                }));

                this.chart.setOption({
                    series: [{
                        data: pieData
                    }]
                });
            }
        } catch (error) {
            console.log(`错误: ${error.message}`);
        }
    }

    // 属性变化时更新图表
    attributeChangedCallback(name, oldValue, newValue) {
        if (name && newValue && oldValue !== newValue) {
            const currentOptions = this.chart.getOption();
            if (!currentOptions) return;

            switch (name) {
                case 'title-text':
                    currentOptions.title[0].text = newValue;
                    this.chart.setOption(currentOptions);
                    break;

                case 'title-color':
                    currentOptions.title[0].textStyle.color = newValue;
                    this.chart.setOption(currentOptions);
                    break;

                case 'title-font-size':
                    currentOptions.title[0].textStyle.fontSize = parseInt(newValue);
                    this.chart.setOption(currentOptions);
                    break;

                case 'legend-color':
                    if (!currentOptions.legend[0]) currentOptions.legend[0] = {};
                    if (!currentOptions.legend[0].textStyle) currentOptions.legend[0].textStyle = {};
                    currentOptions.legend[0].textStyle.color = newValue;
                    this.chart.setOption(currentOptions);
                    break;

                case 'legend-position':
                    if (!currentOptions.legend[0]) currentOptions.legend[0] = {};
                    // 重置位置属性
                    currentOptions.legend[0].left = undefined;
                    currentOptions.legend[0].right = undefined;
                    currentOptions.legend[0].top = undefined;
                    currentOptions.legend[0].bottom = undefined;
                    currentOptions.legend[0].center = undefined;

                    // 设置新位置
                    currentOptions.legend[0].orient = newValue.includes('top') || newValue.includes('bottom') ? 'horizontal' : 'vertical';
                    if (newValue.includes('left')) currentOptions.legend[0].left = 'left';
                    if (newValue.includes('right')) currentOptions.legend[0].right = 'right';
                    if (newValue.includes('top')) currentOptions.legend[0].top = 'top';
                    if (newValue.includes('bottom')) currentOptions.legend[0].bottom = 'bottom';
                    if (newValue === 'center') currentOptions.legend[0].center = 'center';

                    this.chart.setOption(currentOptions);
                    break;

                case 'color-list':
                    const colorArray = newValue.split(',');
                    currentOptions.color = colorArray;
                    this.chart.setOption(currentOptions);
                    break;

                case 'radius':
                    if (currentOptions.series.length > 0) {
                        currentOptions.series[0].radius = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;

                case 'center':
                    if (currentOptions.series.length > 0) {
                        currentOptions.series[0].center = newValue.split(',').map(item => item.trim());
                        this.chart.setOption(currentOptions);
                    }
                    break;

                case 'label-show':
                    if (currentOptions.series.length > 0) {
                        const show = newValue !== 'false';
                        currentOptions.series[0].label.show = show;
                        currentOptions.series[0].labelLine.show = show && currentOptions.series[0].label.position === 'outside';
                        this.chart.setOption(currentOptions);
                    }
                    break;

                case 'label-position':
                    if (currentOptions.series.length > 0) {
                        currentOptions.series[0].label.position = newValue;
                        currentOptions.series[0].labelLine.show = currentOptions.series[0].label.show && newValue === 'outside';
                        this.chart.setOption(currentOptions);
                    }
                    break;

                case 'echart-timer':
                    this.setTimer(parseInt(newValue) * 1000);
                    break;

                case 'echart-timer-script':
                    if (this.echarttimerscript === "") {
                        clearInterval(this.timerId);
                    } else {
                        this.setTimer(parseInt(this.echarttimer) * 1000);
                    }
                    break;

                case 'echart-init-script':
                    if (this.echartinitscript !== "") {
                        try {
                            eval(this.echartinitscript);
                        } catch (error) {
                            console.log(error.message);
                        }
                    }
                    break;

                case 'data-url':
                    this.updateData();
                    break;
            }
        }
    }
}

// 定义新的 HTML 元素
customElements.define('pie-chart-component-sjbz', PieChartComponentSjbz);
